const WebSocket = require('ws');
const cheerio = require('cheerio'); // 引入 cheerio
const { getOpenAIResponse } = require('./open.js');
const ws = new WebSocket('ws://localhost:8080');
const { exec } = require('child_process');
const iconv = require('iconv-lite');

// exec(`powershell.exe Add-Type -AssemblyName System.speech; $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer; $speak.Rate = 5; $speak.Speak([Console]::In.ReadLine()); exit`).stdin.end(iconv.encode('别不信', 'gbk'));



// return

function convertMarkdownToText(markdown) {
    // 去除粗体、斜体、代码块等 Markdown 语法
    return markdown
      .replace(/\*\*(.*?)\*\*/g, '$1')  // 去除粗体
      .replace(/\*(.*?)\*/g, '$1')      // 去除斜体
      .replace(/`(.*?)`/g, '$1')        // 去除代码块
      .replace(/\n\n/g, '\n')           // 替换两个换行符为一个换行符
      .replace(/\n/g, ' ');             // 将换行符替换为空格
  }

async function Msg(msg) {
    try {
        const response = await getOpenAIResponse(msg);
        console.log('OpenAI Response:', response);
        // 将文本转换成语音
        exec(`powershell.exe Add-Type -AssemblyName System.speech; $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer; $speak.Rate = 5; $speak.Speak([Console]::In.ReadLine()); exit`).stdin.end(iconv.encode(convertMarkdownToText(response), 'gbk'));
    } catch (error) {
      console.error('Error in main function:', error);
    }
  }

let old = []

// 连接成功
ws.on('open', () => {
  console.log('Connected to WebSocket server');
});

// 接收到消息
ws.on('message', (data) => {
  if (data instanceof Buffer) {
    if(!data) return
    // 如果数据是 Buffer 类型，转换为字符串
    const html = data.toString();
    // console.log('Received HTML:', html);
    // 解析 HTML 字符串
    const $ = cheerio.load(html);

    // 提取数据
    const messages = [];
    
    $('.ReactVirtualized__Grid__innerScrollContainer > div').each((index, element) => {
      const $element = $(element);

      // 提取用户名称
      const nameElement = $element.find('.chatItemNickName--AetDL');
      const name = nameElement.text().trim();
      
      // 提取用户消息
      const msgElement = $element.find('.chatItemDesc--KHShO');
      const msg = msgElement.text().trim();
      
      if (name && msg) {
        messages.push({ name, msg });
      }
    });
    if(!messages.length) return
    if(old.length != messages.length) {
        console.log('当前弹幕内容:', messages);
        console.log('正在向豆包发送API....', messages[messages.length - 1].msg)
        Msg(messages[messages.length - 1].msg)
        old = messages
    }

    

  } else {
    // 处理其他类型的数据（例如字符串）
    console.log('Received data:', data);
  }
});



// 连接关闭
ws.on('close', () => {
  console.log('Disconnected from WebSocket server');
});

// 连接错误
ws.on('error', (error) => {
  console.error('WebSocket error:', error);
});

